package com.edooschool.oral.arithmetic.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.WebUtils;

import com.demo2do.core.entity.result.HttpResult;
import com.edooschool.oral.arithmetic.service.OralService;
import com.edooschool.oral.arithmetic.web.interceptor.UserContext;
import com.edooschool.oral.arithmetic.web.interceptor.UserContextType;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("")
public class OralRestController {
    
    private static final Logger logger = LoggerFactory.getLogger(OralRestController.class);
    
    @Autowired
    private OralService oralService;
    
    private static final String OPENID_KEY = "edooschool-wechat-openid";
    
    /**
     * 
     * @param current
     * @param marks
     * @param type
     * @param roundId
     * @param request
     * @return
     */
    @UserContext(type = UserContextType.WECHAT_BASE)
    @RequestMapping(value = "/oral-share", method = RequestMethod.POST,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onShare(@RequestParam("current") String current,
                                            @RequestParam("marks") String marks,
                                            @RequestParam("type") String type,
                                            @RequestParam(value = "round", required = false) Long roundId,
                                            HttpServletRequest request) {
        
        HttpResult httpResult = new HttpResult();
        
        Cookie openidCookie =WebUtils.getCookie(request, OPENID_KEY);
        
        if(openidCookie == null) {
            return httpResult.fail("400").message("请在微信环境打开");
        }
        
        try {
            
            String openid = openidCookie.getValue();
            oralService.shareOralArithmetic(openid, roundId, current, marks, type);
            httpResult.success().message("分享成功");
            
        } catch (Exception e) {
            logger.error("#onShare() - sahre oralRound faild!", e);
            httpResult.fail("500").message("分享失败");
        }
        
        return httpResult;
    }
}
